<template>
  <nut-dialog no-cancel-btn title="温馨提示" content="当前影院场次已变更，暂时无法获取座位信息，请稍后再试。" v-model:visible="tipFlag">
    <template v-slot:footer>
      <div class="flex-content flex-content-light">
        <nut-button block color="linear-gradient(to right, #5232B7,#7237BC)" @click="onOk">确定</nut-button>
      </div>
    </template>
  </nut-dialog>

  <div class="select-seat-container" v-if="options.loadComplete" ref="scrollDiv" style="height: 100%; overflow: auto">
    <Header v-if="currentShowInfo" :info="currentShowInfo"></Header>
    <SeatDemos v-if="options.loadComplete" :list="options.seatTypeList"></SeatDemos>
    <AreaDemos v-if="currentAreaList" :list="currentAreaList"></AreaDemos>
    <SeatView :arealist="currentAreaList ? currentAreaList : []" :options="options" @onchange="clickSeat"></SeatView>
    <Footer :selected-seat="options.selectedSeat" :currentShowId="currentShowId" :seatList="options.seatList"
      :currentShowInfo="currentShowInfo" :arealist="currentAreaList ? currentAreaList : []" @onCloseItem="onCloseItem"
      :rateList="rateList" v-if="rateList">
    </Footer>
    <ua-loading v-model="loadingstyle" background="rgba(0,0,0,.5)">
      <template #spinner>
        <span class="custom-loading">
          <em></em><em></em><em></em><em></em><em></em>
        </span>
      </template>
      <template #text>
        <div style="color: #fff; font-size: 14px; font-weight: 700">
          Loading...
        </div>
      </template>
    </ua-loading>
  </div>
</template>
<script lang="ts">
// import { needLogin } from "../../utils/needLoginHook";
// export default {
//     name: "SelectSeat",
//     mixins: [needLogin],
// };
</script>
<script setup lang="ts">
import Taro from "@tarojs/taro";
import uaLoading from "../../component/ua-loading/ua-loading.vue";
import { storeToRefs } from "pinia";
import { useMovieStore } from "../../store";
import Header from "./header.vue";
import SeatDemos from "./seat-demos.vue";
import AreaDemos from "./area-demos.vue";
import SeatView from "./seat-view.vue";
import Footer from "./footer.vue";
import { onMounted, ref, nextTick } from "vue";
import * as seatConfig from "./seat_config";
import * as cinemaApi from "../../api/cinema";
const router = Taro.useRouter();
const currentShowId: any = ref("");
const currentShowInfo: any = ref(null);
const currentFilmInfo: any = ref(null);
const rateList: any = ref([]);
const cinemaLineVo = ref({});
const currentAreaList: any = ref(null);
const tipFlag = ref(false);
const movieStore = useMovieStore();
const { cinemaLineList } = storeToRefs(movieStore);
const options: any = ref({
  seatList: [],
  selectedSeat: [],
  hallName: undefined,
  scaleValue: 1,
  hidden: "hidden",
  maxSelect: 4,
  totalPrice: 0,
  loadComplete: false,
  timer: null,
  seatArea: 0,
  seatTypeList: [],
  rpxToPx: 0,
  maxY: 0,
  maxX: 0,
  seatScale: 0,
  seatScaleHeight: 0,
  seatToolArr: [],
  screenWidth: 0,
  cinemaName: undefined,
  x: 0,
  y: 0,
});
const clickTimer = ref(null);

const scrollDiv = ref(null);
const onOk = () => {
  if (clickTimer.value) {
    clearTimeout(clickTimer.value);
  }
  clickTimer.value = setTimeout(() => {
    Taro.navigateBack({ delta: 2 });
  }, 1000);
};
const loadingstyle = ref(true);
onMounted(() => {
  currentShowId.value = router.params.showid;
  getAppInfo();
  getData();
});
//计算限价比例
const calRate = () => {
  if (!cinemaLineVo.value?.limitLow) {
    rateList.value = [
      {
        id: 1,
        name: "78折",
        zhe: 0.78,
      },
      {
        id: 2,
        name: "8折",
        zhe: 0.8,
      },
      {
        id: 3,
        name: "85折",
        zhe: 0.85,
      },
      {
        id: 4,
        name: "9折",
        zhe: 0.9,
      },
    ];
    return;
  }
  // 使用函数生成介于 78% 到 100% 之间的四个均等比例
  const minPercent = cinemaLineVo.value?.limitLow / 100; // 最低的比例 78%
  const maxPercent = 1.0; // 最高的比例 100%
  const numberOfPercentages = 5; // 要生成的比例数量

  const generatedPercentages = generateEqualPercentages(
    minPercent,
    maxPercent,
    numberOfPercentages
  );
  rateList.value = generatedPercentages;
};
//生成比例
const generateEqualPercentages = (minPercentage, maxPercentage, count) => {
  const step = (maxPercentage - minPercentage) / (count - 1);
  const percentages = [];

  for (let i = 0; i < count - 1; i++) {
    const currentPercentage = minPercentage + step * i;
    percentages.push({
      id: i + 1,
      name: `${Math.round(currentPercentage * 100)}折`,
      zhe: currentPercentage.toFixed(2),
    });
  }
  return percentages;
};
//获取座位数据
const getData = async () => {
  Taro.showLoading({
    title: "座位加载中...",
  });
  loadingstyle.value = true;
  const data = {
    showId: router.params.showid,
  };
  const res: any = await cinemaApi.seat(data);
  if (res.state == 202) {
    loadingstyle.value = false;
    Taro.hideLoading();

    tipFlag.value = true;

    return;
  }

  currentAreaList.value = res.data.regions;
  currentShowInfo.value = res.data.cinemaShow;
  cinemaLineVo.value = res.data.cinemaLineVo;
  const seats = formatSeatsData(res.data.seats);
  const seatList = seats.filter((item) => item.seatNo);

  initSeatArea(seatList);
  calRate();

  loadingstyle.value = false;
  Taro.hideLoading();
};
// 整理远程座位数据格式
const formatSeatsData = (data) => {
  const arr = data.map((item: any) => {
    const res = {
      // id: item.seatId,
      row: String(item.row),
      col: String(item.col),
      gRow: Number(item.row),
      gCol: Number(item.col) + 1,
      type: "0-2",
      // flag: "0",
      price: item.price,
      seatNo: item.seatNo,
      areaId: item.regionName,
      seatType: item.seatType,
      canUse: item.canUse,
    };
    if (item.row && item.seatNo && !item.seatType && item.canUse) {
      res.type = "0";
    } else if (item.seatNo && !item.seatType && !item.canUse) {
      res.type = "0-2";
    } else if (item.seatNo && item.seatType === "L" && item.canUse) {
      res.type = "1";
    } else if (item.seatNo && item.seatType === "R" && item.canUse) {
      res.type = "2";
    } else if (item.seatNo && item.seatType === "L" && !item.canUse) {
      res.type = "1-2";
    } else if (item.seatNo && item.seatType === "R" && !item.canUse) {
      res.type = "2-2";
    }
    // if (item.status && !item.lovestatus) {
    //     res.type = "0";
    // } else if (!item.status && !item.lovestatus) {
    //     res.type = "0-2";
    // } else if (!item.status && item.lovestatus) {
    //     res.type = "1";
    // } else if (item.status === "L" && item.lovestatus === 1) {
    //     res.type = "1-2";
    // } else if (item.status === "N" && item.lovestatus === 2) {
    //     res.type = "2";
    // } else if (item.status === "LK" && item.lovestatus === 2) {
    //     res.type = "2-2";
    // }
    return res;
  });
  return arr;
};
// 获取系统信息
const getAppInfo = () => {
  const systemInfo: any = Taro.getSystemInfoSync();
  const seatArea =
    systemInfo.screenHeight - (500 * systemInfo.screenWidth) / 750;
  options.value.seatArea =
    seatArea > 0 ? seatArea : systemInfo.screenHeight * 0.6;
  options.value.rpxToPx = systemInfo.screenWidth / 750;
  options.value.screenWidth = systemInfo.screenWidth;
};
const onCloseItem = (e) => {
  let seatList = options.value.seatList;
  const index = seatList.findIndex((item) => {
    return e.col == item.col && e.row == item.row;
  });

  processSelected(index);
};
const initSeatArea = (seats) => {
  // const showInfo = currentShowInfo.value;
  const seatTypeList = seatConfig.seatTypeList;
  const seatList = prosessSeatList(seats, seatTypeList);
  options.value.hallName = currentShowInfo.value.hallName;
  options.value.cinemaName = currentShowInfo.value.cinemaName;
  options.value.seatTypeList = seatTypeList;
  options.value.seatList = seatList;
  options.value.selectedSeat = [];
  options.value.totalPrice = 0;
  options.value.hidden = "hidden";
  //计算X和Y坐标最大值
  prosessMaxSeat(seatList);
  //计算左侧座位栏的数组
  seatToolArr();
  //按每排生成座位数组对象
  creatSeatMap();
  //确认最佳坐标座位
  creatBestSeat();
};

const prosessSeatList = (seatList, seatTypeList) => {
  let resSeatList = seatList;
  resSeatList.forEach((element) => {
    // 获取座位的类型的首字母
    let firstNumber = element.type.substr(0, 1);
    // 在原来的对象中加入两个属性  otherLoveSeatIndex 对应情侣座位的原数组下标 otherLoveSeatId  对应情侣座位的Id
    element.otherLoveSeatIndex = null;
    element.otherLoveSeatId = null;
    // 座位的类型的首字母为 '1' 是情侣首座 处理情侣首座位
    if (firstNumber === "L") {
      for (const index in resSeatList) {
        if (
          resSeatList[index].gRow === element.gRow &&
          resSeatList[index].gCol === element.gCol + 1
        ) {
          element.otherLoveSeatIndex = index;
          element.otherLoveSeatId = resSeatList[index].id;
        }
      }
    }
    // 座位的类型的首字母为 '2' 是情侣次座 处理情侣次座位
    if (firstNumber === "R") {
      for (const index in resSeatList) {
        if (
          resSeatList[index].gRow === element.gRow &&
          resSeatList[index].gCol === element.gCol - 1
        ) {
          element.otherLoveSeatIndex = index;
          element.otherLoveSeatId = resSeatList[index].id;
        }
      }
    }
    // 加载座位的图标
    let seatType = seatTypeList;
    for (const key in seatType) {
      // 加载每个座位的初始图标defautIcon 和 当前图标 nowIcon
      if (element.type === seatType[key].type) {
        element.nowIcon = seatType[key].icon;
        element.defautIcon = seatType[key].icon;
      }
      // 根据首字母找到对应的被选中图标
      if (firstNumber + "-1" === seatType[key].type) {
        element.selectedIcon = seatType[key].icon;
      }
      // 根据首字母找到对应的被选中图标
      if (firstNumber + "-2" === seatType[key].type) {
        element.soldedIcon = seatType[key].icon;
      }
      // 根据首字母找到对应的被选中图标
      if (firstNumber + "-3" === seatType[key].type) {
        element.fixIcon = seatType[key].icon;
      }
    }
    // 如果座位是已经售出 和 维修座位 加入属性canClick 判断座位是否可以点击
    if (
      element.defautIcon === element.soldedIcon ||
      element.defautIcon === element.fixIcon
    ) {
      element.canClick = false;
    } else {
      element.canClick = true;
    }
  });
  return resSeatList;
};
//计算最大座位数,生成影厅图大小
const prosessMaxSeat = (value) => {
  let seatList = value;
  let maxY: any = 0;
  for (let i = 0; i < seatList.length; i++) {
    let tempY = seatList[i].gRow;
    if (parseInt(tempY) > parseInt(maxY)) {
      maxY = tempY;
    }
  }
  let maxX: any = 0;
  for (var i = 0; i < seatList.length; i++) {
    var tempX = seatList[i].gCol;
    if (parseInt(tempX) > parseInt(maxX)) {
      maxX = tempX;
    }
  }
  let seatRealWidth = parseInt(maxX) * 70 * options.value.rpxToPx;
  let seatRealheight = parseInt(maxY) * 70 * options.value.rpxToPx;
  let seatScale = 1;
  let seatScaleX = 1;
  let seatScaleY = 1;
  let seatAreaWidth = 630 * options.value.rpxToPx;
  let seatAreaHeight = options.value.seatArea - 200 * options.value.rpxToPx;
  if (seatRealWidth > seatAreaWidth) {
    seatScaleX = seatAreaWidth / seatRealWidth;
  }
  if (seatRealheight > seatAreaHeight) {
    seatScaleY = seatAreaHeight / seatRealheight;
  }
  if (seatScaleX < 1 || seatScaleY < 1) {
    seatScale = seatScaleX < seatScaleY ? seatScaleX : seatScaleY;
  }
  options.value.maxY = parseInt(maxY);
  options.value.maxX = parseInt(maxX);
  options.value.seatScale = seatScale;
  options.value.seatScaleHeight = seatScale * 70 * options.value.rpxToPx;
};
// 座位左边栏的数组
const seatToolArr = () => {
  let seatToolArr: any = [];
  let yMax = options.value.maxY;
  let seatList: any = options.value.seatList;
  for (let i = 1; i <= yMax; i++) {
    let el: any = "";
    for (let j = 0; j < seatList.length; j++) {
      if (parseInt(seatList[j].gRow) === i) {
        el = seatList[j].row;
      }
    }
    seatToolArr.push(el);
  }
  options.value.seatToolArr = seatToolArr;
};
// 根据seatList 生成一个类map的对象 key值为gRow坐标 value值为gRow为key值的数组
const creatSeatMap = () => {
  let seatList: any = options.value.seatList;
  var obj = {};
  for (let index in seatList) {
    let seatRowList = seatList[index].gRow;
    if (seatRowList in obj) {
      // 原本数组下标
      seatList[index].orgIndex = index;
      obj[seatRowList].push(seatList[index]);
    } else {
      let seatArr: any = [];
      // 原本数组下标
      seatList[index].orgIndex = index;
      seatArr.push(seatList[index]);
      obj[seatRowList] = seatArr;
    }
  }
  options.value.seatMap = obj;
};
//生成最佳座位
const creatBestSeat = () => {
  // 优先左侧
  const bestX = parseInt(options.value.maxX) / 2 + 1;
  // 四舍五入  0.618为黄金分割比例
  const bestY = Math.round(options.value.maxY * 0.618);
  options.value.bestX = bestX;
  options.value.bestY = bestY;
  options.value.loadComplete = true;
};
// 点击每个座位触发的函数
const clickSeat = (event) => {
  const index = event.index;
  // let index = event.currentTarget.dataset.index;
  if (options.value.seatList[index].canClick) {
    if (
      options.value.seatList[index].nowIcon ===
      options.value.seatList[index].selectedIcon
    ) {
      processSelected(index);
    } else {
      processUnSelected(index);
      const container = scrollDiv.value;
      container.scrollTo({
        top: container.scrollHeight,
        behavior: "smooth",
      });
    }
  }
  if (options.value.selectedSeat.length == 0) {
    options.value.hidden = "hidden";
  }

  let _selectedSeatList = options.value.selectedSeat;
  let totalPrice = 0;
  for (const key in _selectedSeatList) {
    let price = parseInt(_selectedSeatList[key].price);
    totalPrice += price;
  }
  options.value.totalPrice = totalPrice;
};
// 处理已选的座位
const processSelected = (index) => {
  let _selectedSeatList = options.value.selectedSeat;
  let seatList = options.value.seatList;
  let otherLoveSeatIndex = seatList[index].seatType;
  if (otherLoveSeatIndex) {
    // 如果是情侣座位
    // 改变这些座位的图标为初始图标
    if (otherLoveSeatIndex === "L") {
      seatList[index].nowIcon = seatList[index].defautIcon;
      seatList[index + 1].nowIcon = seatList[index + 1].defautIcon;
      for (const key in _selectedSeatList) {
        // 移除id一样的座位
        if (
          _selectedSeatList[key].col === seatList[index].col &&
          _selectedSeatList[key].row === seatList[index].row
        ) {
          _selectedSeatList.splice(key, 1);
        }
      }
      // 移除对应情侣座位
      for (const key in _selectedSeatList) {
        if (
          _selectedSeatList[key].col === seatList[index + 1].col &&
          _selectedSeatList[key].row === seatList[index + 1].row
        ) {
          _selectedSeatList.splice(key, 1);
        }
      }
    } else {
      seatList[index].nowIcon = seatList[index].defautIcon;
      seatList[index - 1].nowIcon = seatList[index - 1].defautIcon;
      for (const key in _selectedSeatList) {
        // 移除id一样的座位
        if (
          _selectedSeatList[key].col === seatList[index].col &&
          _selectedSeatList[key].row === seatList[index].row
        ) {
          _selectedSeatList.splice(key, 1);
        }
      }
      // 移除对应情侣座位
      for (const key in _selectedSeatList) {
        if (
          _selectedSeatList[key].col === seatList[index - 1].col &&
          _selectedSeatList[key].row === seatList[index - 1].row
        ) {
          _selectedSeatList.splice(key, 1);
        }
      }
    }
  } else {
    // 改变这些座位的图标为初始图标 并 移除id一样的座位
    seatList[index].nowIcon = seatList[index].defautIcon;
    for (const key in _selectedSeatList) {
      if (_selectedSeatList[key].seatNo === seatList[index].seatNo) {
        _selectedSeatList.splice(key, 1);
      }
    }
  }
  options.value.selectedSeat = _selectedSeatList;
  options.value.seatList = seatList;
};
// 处理未选择的座位
const processUnSelected = (index) => {
  let _selectedSeatList = options.value.selectedSeat;
  let seatList = options.value.seatList;
  // let otherLoveSeatIndex = seatList[index].otherLoveSeatIndex;
  let otherLoveSeatIndex = seatList[index].seatType;

  if (otherLoveSeatIndex) {
    if (otherLoveSeatIndex == "L") {
      // 如果选中的是情侣座位 判断选择个数不大于 maxSelect
      if (_selectedSeatList.length >= options.value.maxSelect - 1) {
        return;
      }
      // 改变这些座位的图标为已选择图标
      seatList[index].nowIcon = seatList[index].selectedIcon;
      seatList[index + 1].nowIcon = seatList[index + 1].selectedIcon;
      // 记录 orgIndex属性 是原seatList数组中的下标值
      seatList[index].orgIndex = index;
      seatList[index + 1].orgIndex = index + 1;
      // 把选择的座位放入到已选座位数组中
      let temp = { ...seatList[index] };
      let tempLove = { ...seatList[index + 1] };
      _selectedSeatList.push(temp);
      _selectedSeatList.push(tempLove);
    } else {
      // 如果选中的是情侣座位 判断选择个数不大于 maxSelect
      if (_selectedSeatList.length >= options.value.maxSelect - 1) {
        return;
      }
      // 改变这些座位的图标为已选择图标
      seatList[index].nowIcon = seatList[index].selectedIcon;
      seatList[index - 1].nowIcon = seatList[index - 1].selectedIcon;
      // 记录 orgIndex属性 是原seatList数组中的下标值
      seatList[index].orgIndex = index;
      seatList[index - 1].orgIndex = index - 1;
      // 把选择的座位放入到已选座位数组中
      let temp = { ...seatList[index] };
      let tempLove = { ...seatList[index - 1] };
      _selectedSeatList.push(temp);
      _selectedSeatList.push(tempLove);
    }
  } else {
    // 如果选中的是非情侣座位 判断选择个数不大于 maxSelect
    if (_selectedSeatList.length >= options.value.maxSelect) {
      Taro.showToast({
        title: "最多只能选择" + options.value.maxSelect + "个座位哦~",
        icon: "none",
        duration: 2000,
      });
      return;
    }
    // 改变这些座位的图标为已选择图标
    seatList[index].nowIcon = seatList[index].selectedIcon;
    // 记录 orgIndex属性 是原seatList数组中的下标值
    seatList[index].orgIndex = index;
    // 把选择的座位放入到已选座位数组中
    let temp = { ...seatList[index] };
    _selectedSeatList.push(temp);
  }
  options.value.selectedSeat = _selectedSeatList;
  options.value.seatList = seatList;
  options.value.hidden = "";
};
</script>
<style lang="scss">
.select-seat-container {
  display: flex;
  flex-direction: column;

  .custom-loading {
    display: inline-flex;
    align-items: flex-end;
    gap: 5px;
    min-height: 45px;
  }

  .custom-loading em {
    background: #5232b7;
    border-radius: 6px;
    display: inline-block;
    height: 100%;
    width: 10px;
    animation: animHeart 2s linear infinite;
  }

  @keyframes animHeart {
    0%,
    100% {
      height: 15px;
      background: #5232b7;
    }

    50% {
      height: 45px;
      background: #999;
    }
  }

  .custom-loading em:nth-child(2) {
    animation-delay: 0.2s;
  }

  .custom-loading em:nth-child(3) {
    animation-delay: 0.4s;
  }

  .custom-loading em:nth-child(4) {
    animation-delay: 0.6s;
  }

  .custom-loading em:nth-child(5) {
    animation-delay: 0.8s;
  }
}

/*
*页面最下方确认选座区域
*/

.orderComfirm {
  background: #fff;
  position: fixed;
  display: flex;
  bottom: 0rpx;
  width: 100%;
  line-height: 100rpx;
  z-index: 3;
}

/*
*页面最下方价格区域
*/

.orderPrice {
  text-indent: 30rpx;
  color: black;
  height: 100rpx;
  width: 60%;
}

/*
*页面最下方价格字体样式
*/

.orderPrice text {
  color: #5232b7;
}

/*
*页面最下方确认选座区域渐变色
*/

.comfirm {
  font-weight: 900;
  text-align: center;
  color: white;
  width: 100%;
  background: linear-gradient(to right, #c26dfe, #6f50f5);
  height: 100rpx;
}

/*
*用户选中的座位区域
*/

.selectSeatInfo {
  background: #fff;
  position: fixed;
  bottom: 100rpx;
  height: 80rpx;
  width: 100%;
  padding: 10rpx 0;
}

/*
*用户选中的座位详情滑块
*/

.scrollSeat {
  height: 90rpx;
  white-space: nowrap;
}

/*
*每块用户选中的座位详情
*/

.scrollItem {
  border: 1rpx solid #bbb;
  border-radius: 10rpx;
  width: 180rpx;
  display: inline-block;
  margin-left: 20rpx;
  position: relative;
}

/*
* 快速选座模块
*/

.quickItem {
  border: 1rpx solid #bbb;
  color: #aaa;
  font-size: 28rpx;
  border-radius: 10rpx;
  width: 160rpx;
  height: 75rpx;
  line-height: 75rpx;
  text-align: center;
  display: inline-block;
  margin-left: 20rpx;
  position: relative;
}

/*
*每块用户选中的座位详情上方文字
*/

.scrollTextTop {
  color: #555;
  text-indent: 30rpx;
  line-height: 25rpx;
  font-size: 26rpx;
  height: 25rpx;
  margin-top: 10rpx;
}

/*
*每块用户选中的座位详情下方文字
*/

.scrollTextBottom {
  font-weight: 600;
  font-size: 26rpx;
  color: #5232b7;
  text-indent: 40rpx;
  height: 25rpx;
  line-height: 25rpx;
  margin: 10rpx 0;
}

/*
*每块用户选中的座位详情关闭按钮
*/

.scrollItem image {
  position: absolute;
  z-index: 2;
  width: 30rpx;
  height: 30rpx;
  right: 10rpx;
  top: 50%;
  transform: translateY(-50%);
}

.seatAreaTip {
  position: relative;
  width: 750rpx;
  height: 50rpx;
  line-height: 50rpx;
  text-align: center;
  font-size: 16rpx;
  color: rgba(0, 0, 0, 0.1);
  border-top: 1rpx dashed rgba(0, 0, 0, 0.1);
}
</style>
